<template>
  <a-form
    ref="formRef"
    :model="productInfo"
    :rules="rules"
    :label-col="{ span: 5 }"
    :wrapper-col="{ span: 17 }"
  >
    <a-form-item label="商品名称" name="name">
      <a-input v-model:value="productInfo.name" placeholder="请输入商品名称" />
    </a-form-item>
    <a-form-item label="商品价格">
      <a-input-number
        id="inputNumber"
        placeholder="元"
        v-model:value="productInfo.price"
        :min="0"
      />
    </a-form-item>
    <a-form-item label="商品描述" name="description">
      <a-textarea
        v-model:value="productInfo.description"
        placeholder="请输入商品描述"
        :auto-size="{ minRows: 5, maxRows: 10 }"
      />
    </a-form-item>
    <a-form-item label="商品分类">
      <a-select
        placeholder="请选择商品分类"
        v-model:value="productInfo.classesId"
      >
        <a-select-option
          v-for="type in classes"
          :value="type.id"
          :key="type.id"
          >{{ type.name }}</a-select-option
        >
      </a-select>
    </a-form-item>
    <a-form-item label="商品图片">
      <a-button @click="upload">上传图片</a-button>
      <input
        id="chkFile"
        ref="fileBtn"
        type="file"
        @change="toBase()"
        style="display: none"
      /><br />
      <img id="showImg" :src="productInfo.picture" style="margin-top: 20px" />
      <br />
      <textarea ref="picture" id="showText" v-show="false"></textarea>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit">提交</a-button>
      <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import PubSub from "pubsub-js";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import {
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  toRaw,
  createVNode,
} from "vue";
import { toBase64 } from "../../../utils";
import {
  reqUpdateProduct,
  reqAddProduct,
  reqDeleteProduct,
} from "../../../api";
import { message, Modal } from "ant-design-vue";

// 上传图片的hooks
function useUploadPicture() {
  const fileBtn = ref();

  function upload() {
    fileBtn.value.click();
  }

  function toBase() {
    toBase64();
  }

  return {
    upload,
    fileBtn,
    toBase,
  };
}

// 商品分类的hooks
function useProductClasses() {
  const classes = ref([]);
  onMounted(() => {
    PubSub.subscribe("classesInfo", (_, item) => {
      classes.value = item;
    });
  });
  return {
    classes,
  };
}

// 商品表单的hooks
function useProduct(hiddenModal, initProductTable) {
  const rules = {
    name: [
      {
        required: true,
        message: "请输入商品名称",
        trigger: "blur",
      },
    ],
    description: [
      {
        required: true,
        message: "请输入商品描述",
        trigger: "blur",
      },
    ],
  };

  const formRef = ref();
  const picture = ref("");

  const productInfo = reactive({});

  const isAdd = ref(false);

  // 监听更新isAdd
  PubSub.subscribe("updateIsAdd", (_, item) => {
    isAdd.value = item.isAdd;
  });

  // 监听编辑商品
  PubSub.subscribe("productInfo", (_, item) => {
    Object.keys(item).forEach((key) => {
      productInfo[key] = item[key];
    });
  });

  //监听添加商品
  PubSub.subscribe("isAdd", (_, item) => {
    isAdd.value = item.isAdd;
    Object.keys(productInfo).forEach((key) => {
      productInfo[key] = "";
    });
  });

  // 监听删除商品
  PubSub.subscribe("deleteProduct", (_, item) => {
    Modal.confirm({
      title: "确认删除这个商品吗 ?",
      icon: createVNode(ExclamationCircleOutlined),
      content: "此操作不可撤销",
      okText: "Yes",
      okType: "danger",
      cancelText: "No",

      onOk() {
        toDeleteProduct(item.id);
      },

      onCancel() {
        message.info("已取消删除");
      },
    });
  });

  // 发送删除商品的请求
  async function toDeleteProduct(id) {
    const result = await reqDeleteProduct(id);
    showMessage(result);
  }

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        if (isAdd.value) {
          toAddProduct(toRaw(productInfo));
        } else {
          toUpdataProduct(toRaw(productInfo));
        }
      })
      .catch((error) => {
        console.log("error", error);
      });
  };

  // 发送更新商品的异步请求
  async function toUpdataProduct(product) {
    const img = picture.value.value;
    if (img.trim()) {
      product.picture = picture.value.value;
    }
    const result = await reqUpdateProduct(product);
    showMessage(result);
  }

  function showMessage(result) {
    if (result.success) {
      message.success(result.message);
      initProductTable();
    } else {
      message.error(result.message);
    }
    hiddenModal();
  }

  // 发送添加商品的异步请求
  async function toAddProduct(product) {
    product.picture = picture.value.value;
    const result = await reqAddProduct(product);
    showMessage(result);
  }

  const resetForm = () => {
    formRef.value.resetFields();
  };

  onBeforeUnmount(() => {
    PubSub.clearAllSubscriptions();
  });

  return {
    rules,
    productInfo,
    onSubmit,
    resetForm,
    formRef,
    picture,
  };
}

export default {
  name: "ProductForm",
  props: ["hiddenModal", "initProductTable"],
  setup(props) {
    const { hiddenModal, initProductTable } = props;
    return {
      ...useProduct(hiddenModal, initProductTable),
      ...useProductClasses(),
      ...useUploadPicture(),
    };
  },
};
</script>

<style>
#showImg {
  width: 300px;
  margin-top: 20px;
}
</style>